package beanstao.util.store.database;

import java.util.List;
import java.util.Map;

import org.dom4j.Element;
import org.dom4j.Node;

import beanstao.util.collections.Pair;
import beanstao.util.reflect.Mirror;
import beanstao.util.setting.Setting;
import beanstao.util.store.database.interfaces.IDbCreator;
import beanstao.util.store.database.interfaces.ISqls;

import com.google.common.collect.Maps;

public class DbOperatorSetting extends Setting<Element>
{

	public ISqls getSqls(String key)
	{
		return _SqlsMap.get(key);
	}

	public IDbCreator getCreator(String key)
	{
		return _CreatorMap.get(key);
	}

	private Map<String, ISqls> _SqlsMap = null;
	private Map<String, IDbCreator> _CreatorMap = null;

	@Override
	protected void fillSettingData(Element element)
	{
		_CreatorMap = Maps.newHashMap();
		_SqlsMap = Maps.newHashMap();

		Element creatorEle = (Element) element.selectSingleNode("creator");
		List<? extends Node> elements = creatorEle.selectNodes("class");
		for (Node node : elements)
		{
			Pair<String, IDbCreator> pair = Mirror.klassbuilder(node);
			if (null == pair)
				continue;
			_CreatorMap.put(pair.getLeft(), pair.getRight());
		}

		Element sqlsEle = (Element) element.selectSingleNode("sqls");
		List<? extends Node> elements2 = sqlsEle.selectNodes("class");
		for (Node node : elements2)
		{
			Pair<String, ISqls> pair = Mirror.klassbuilder(node);
			if (null == pair)
				continue;
			_SqlsMap.put(pair.getLeft(), pair.getRight());
		}

	}

	// =======================

	/**
	 * 本类型的单建实例
	 * 
	 * @return 返回本类型的单建实例(延迟加载,并对多线程进行处理)
	 */
	public static DbOperatorSetting ME()
	{
		return Single.instance;
	}

	/**
	 * 为单建模式设计的内部静态类型
	 */
	static class Single
	{
		/**
		 * 多线程锁
		 */
		static Object lock = new Object();
		static
		{
			synchronized (lock)
			{
				instance = new DbOperatorSetting();
			}
		}
		static DbOperatorSetting instance;
	}

	/**
	 * 针对单建模式,私有化本类型构造函数
	 */
	private DbOperatorSetting()
	{
	}

}
